import 'dart:async';
import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/work_history.dart';
import 'package:kxy_flutter_app/view/my/basic_info/work_history_item_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'work_history_detail_view.dart';

class WorkHistoryListView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return WorkHistoryListViewState();
  }
}

class WorkHistoryListViewState extends State<WorkHistoryListView> {
  RefreshController controller = new RefreshController();
  List<WorkHistory> workHistoryList;
  Future loadFuture;

  @override
  void initState() {
    loadFuture = loadList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('工作经历'),
        actions: [
          FlatButton(
            child: Text('新增'),
            textColor: Theme.of(context).primaryColor,
            padding: EdgeInsets.all(0),
            onPressed: gotoDetail,
          ),
        ],
      ),
      body: FutureBuilder(
        future: loadFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Widget body() {
    if (workHistoryList.length == 0) {
      return EmptyWidget(onRefresh: loadList);
    }

    return SmartRefresher(
      controller: controller,
      enablePullDown: true,
      enablePullUp: false,
      header: RefreshHeader(),
      child: ListView.builder(
        padding: EdgeInsets.all(20),
        itemCount: workHistoryList.length,
        itemBuilder: (cxt, index) {
          var workHistory = workHistoryList[index];
          return GestureDetector(
            child: WorkHistoryItemWidget(
              workHistory: workHistory,
              index: index,
              isLatest: index == workHistoryList.length - 1,
            ),
            onTap: () => gotoDetail(id: workHistory.id),
            onLongPress: () => confirmRemove(workHistory.id),
          );
        },
      ),
      onRefresh: () async {
        await loadList();
        controller.refreshCompleted();
      },
    );
  }

  Future confirmRemove(String id) async {
    var confirm = await showDialog(
        context: context,
        builder: (cxt) {
          return AlertDialog(
            title: Text('提示'),
            content: Text('您确认删除证件吗？'),
            actions: [
              FlatButton(
                child: Text('取消'),
                onPressed: () => Navigator.pop(context, false),
              ),
              FlatButton(
                child: Text('确认'),
                onPressed: () => Navigator.pop(context, true),
              ),
            ],
          );
        });

    if (confirm == true) {
      await remove(id);
      await loadList();
    }
  }

  Future loadList() async {
    var res = await Http.instance.post(
      '/usercenter-app/workhistory/list',
      params: {'userId': Auth.instance.userId},
    );
    if (res.code == 200) {
      setState(() {
        workHistoryList = new List<WorkHistory>();
        (res.data as List).forEach((item) {
          var wh = WorkHistory.fromJson(item);

          // 按时间倒序插入
          workHistoryList.insert(0, wh);
        });
      });
    }
  }

  Future gotoDetail({String id}) async {
    await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (cxt) => WorkHistoryDetailView(id: id),
      ),
    );
    setState(() {
      this.loadFuture = loadList();
    });
  }

  Future remove(String id) async {
    var res = await Http.instance.post(
      '/usercenter-app/workhistory/delete',
      params: {'id': id},
    );
    if (res.code == 200) {
      return res.data;
    }
    return false;
  }
}
